package com.aabte.springcloudlearn.ribbonhystrixcustomerdemo.hystrix;

import com.aabte.springcloudlearn.common.beans.User;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixThreadPoolKey;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Daniel
 */
public class UserCommand extends HystrixCommand<User> {

    private RestTemplate restTemplate;
    private Long userId;

    public UserCommand(HystrixCommandGroupKey group, RestTemplate restTemplate, Long userId) {
        super(group);
        this.restTemplate = restTemplate;
        this.userId = userId;
    }

    public UserCommand(HystrixCommandGroupKey group, HystrixThreadPoolKey threadPool, RestTemplate restTemplate, Long userId) {
        super(group, threadPool);
        this.restTemplate = restTemplate;
        this.userId = userId;
    }

    public UserCommand(HystrixCommandGroupKey group, int executionIsolationThreadTimeoutInMilliseconds, RestTemplate restTemplate, Long userId) {
        super(group, executionIsolationThreadTimeoutInMilliseconds);
        this.restTemplate = restTemplate;
        this.userId = userId;
    }

    public UserCommand(HystrixCommandGroupKey group, HystrixThreadPoolKey threadPool, int executionIsolationThreadTimeoutInMilliseconds, RestTemplate restTemplate, Long userId) {
        super(group, threadPool, executionIsolationThreadTimeoutInMilliseconds);
        this.restTemplate = restTemplate;
        this.userId = userId;
    }

    public UserCommand(Setter setter, RestTemplate restTemplate, Long userId) {
        super(setter);
        this.restTemplate = restTemplate;
        this.userId = userId;
    }

    @Override
    protected User run() throws Exception {
        Map<String, Object> uriVariables = new HashMap<>(1);
        uriVariables.put("userId", userId);
        // 本地请求
        // return restTemplate.getForObject("http://localhost:8011/user/{userId}", User.class, uriVariables);
        // 连接注册中心请求
        return restTemplate.getForObject("http://hello-service/user/{userId}", User.class, uriVariables);
    }
}
